﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;

namespace DbfTools
{
	public static class DataTableExtentions
	{
		public static IEnumerable<DataRow> RowsList(this DataTable table)
		{
			return table == null
				? new DataRow[0]
				: table.Rows.Cast<DataRow>();
		}
		public static IEnumerable<DataRowView> RowsList(this DataView table)
		{
			foreach (DataRowView row in table)
				yield return row;
		}
		public static DataTable AddColumns(this DataTable table, IEnumerable<DataColumn> columns)
		{
			table.Columns.AddRange(columns.ToArray());
			return table;
		}
		public static DataTable AddRows(this DataTable table, IEnumerable<object[]> rows)
		{
			foreach (var row in rows)
				table.Rows.Add(row);
			return table;
		}
		public static DataTable AddRows(this DataTable table, IEnumerable<DataRow> rows)
		{
			foreach (var row in rows)
				table.Rows.Add(row.ItemArray);
			return table;
		}
		public static DataTable SetKey(this DataTable table, params int[] columns)
		{
			table.PrimaryKey = columns.Select(col => table.Columns[col]).ToArray();
			return table;
		}
		public static DataTable SetKey(this DataTable table, params string[] columns)
		{
			table.PrimaryKey = columns.Select(col => table.Columns[col]).ToArray();
			return table;
		}
		public static DataTable SaveCsv(this DataTable table, string fileName)
		{
			var lines =
				from row in table.RowsList()
				select row.ItemArray.Aggregate(new StringBuilder(),
					(accum, item) => accum.Append(item.ToString()));

			using (var file = new StreamWriter(fileName, false, Encoding.GetEncoding(1251)))
				foreach(var line in lines)
					file.WriteLine(line);
			return table;
		}
		public static DataTable ToTable<T>(this IEnumerable<T> list,
			Func<T, object[]> rowGetter, DataColumn[] columns)
		{
			var table = new DataTable();
			table.Columns.AddRange(columns);
			table.AddRows(list.Select(rec => rowGetter(rec)));
			return table;
		}
	}
}
